package com.cyc.service.impl;

import com.cyc.entity.CartItem;
import com.cyc.entity.Product;
import com.cyc.service.CartService;
import com.cyc.service.ProductService;
import com.cyc.util.CookieUtils;
import com.cyc.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    ServletContext servletContext;
    @Autowired
    ProductService productService;

    @Override
    public int addCareService(HttpServletRequest request, HttpServletResponse response, Integer itemId, Integer num) {
        //从cookie中取出商品
        List<CartItem> list=getCartFromCookie(request);
        //判断是否加入购物车
        boolean flag=false;
        for (CartItem c:list){
            if (c.getId().equals(itemId)){
                c.setNum(c.getNum()+num);
                flag=true;
                break;
            }
        }

        //如果没有添加过 就添加进去
        if(!flag){
            Product product = productService.selectByPrimaryKey(itemId);
            CartItem cartItem=new CartItem();
            cartItem.setId(product.getId());
            cartItem.setNum(num);
            cartItem.setName(product.getName());
            cartItem.setPrice(product.getPrice());
            cartItem.setFilename(product.getFilename());
            list.add(cartItem);
        }

        //再存进cookie
        servletContext.setAttribute("shop",list);

        return 1;
    }

    public List<CartItem> getCartFromCookie(HttpServletRequest request){

        try{
            List<CartItem> list = (List<CartItem>)servletContext.getAttribute("shop");
            if (list==null){
                return new ArrayList<>();
            }else {
                return list;
            }
        }catch (Exception e){
            return new ArrayList<>();
        }
    }
}
